package com.dd.controller;

import com.dd.entity.Employee;
import com.dd.entity.R;
import com.dd.enums.HttpEnum;
import com.dd.service.EmployeeService;
import com.dd.util.FileUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;

@RestController
@RequestMapping("/employees")
@CrossOrigin
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    @GetMapping("/getAllEmployee")
    public Object getAllEmployee(){
        return employeeService.getAllEmployee();
    }

    @GetMapping("/page")
    public R<PageInfo<Employee>> getPage(Integer pageNum){
        PageInfo<Employee> pageInfo = employeeService.getPage(pageNum);
        return R.success(pageInfo);
    }

    @PostMapping
    public R saveBook(@Valid Employee employee, MultipartFile employeeImageFile, HttpServletRequest request){
        employee.setEmployeeId(1);
        //得到上传图片的地址
        String imgPath;
        try {
            //ImageUtil为之前添加的工具类
            imgPath = FileUtil.upload(request, employeeImageFile);
            if (imgPath != null) {
                //将上传图片的地址封装到实体类
                employee.setImagePath(imgPath);
                System.out.println("--------------图片上传成功！");
            }else {
                System.out.println("--------------图片上传失效！");
            }
        }catch (IOException e){
            e.printStackTrace();
            System.out.println("---------------图片上传失败！");
        }

        int count = employeeService.saveEmployee(employee);
        return count > 0 ? R.success("新增成功") : R.fail(HttpEnum.ERROR.getCode(), "新增失败");
    }
}
